<?php
/**
 +------------------------------------------------------------------------------
 * 常理解析处理函数
 +----------------------------------------------------------
 * @param string $node 常理节点信息（FILENAME::ARRAY::ARRAYID）
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
$_CONV = array(); //常理加载数组
function CONV($node)
{
	GLOBAL $_CONV;
    $node_array = explode(":",$node);
	if((is_array($node_array) && count($node_array)>=1)){
		$com_dir=CONFIG_PATH.$node_array[0].EXT;

		if(isset($_CONV[$com_dir]) && is_array($_CONV[$com_dir])){
			if(count($node_array) == 1){
				return $_CONV[$com_dir];
			}else{
				return $_CONV[$com_dir][$node_array[1]];
			}
		}else{
			if(is_file($com_dir)) {
				$_CONV[$com_dir] = require_once $com_dir;
				if(count($node_array) == 1){
					return $_CONV[$com_dir];
				}else{
					return $_CONV[$com_dir][$node_array[1]];
				}
			}else{
				return false;
			}
		}
	}else{
		return false;
	}
}

/**
 +------------------------------------------------------------------------------
 * 加载文件函数
 +----------------------------------------------------------
 * @param string $data 数据
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function I($path)
{
	if(is_file($path.EXT) && file_exists($path.EXT)) {
		require $path.EXT;
	}
}

/**
 +------------------------------------------------------------------------------
 * 数据格式化打印处理函数
 +----------------------------------------------------------
 * @param string $data 数据
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function V($data)
{
	if (isset($data)) {
		echo '<pre>';
		var_dump($data);
		echo '</pre>';
	}
}

/**
 +------------------------------------------------------------------------------
 * 接收WEB服务器的GET参数
 +----------------------------------------------------------
 * @param string $name   参数名字
 * @param string $value  默认值
 * @param bool   $escape 是否转义
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function G($name, $value='', $escape = TRUE)
{
	$val = isset($_GET[$name]) && !empty($_GET[$name]) ? $_GET[$name] : $value;
	return $escape == TRUE ? daddslashes(stripslashes_deep($val)): $val;
}

/**
 +------------------------------------------------------------------------------
 * 接收WEB服务器的POST参数
 +----------------------------------------------------------
 * @param string $name   参数名字
 * @param string $value  默认值
 * @param bool   $escape 是否转义
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function P($name, $value='', $escape = TRUE)
{
	$val = isset($_POST[$name]) && !empty($_POST[$name]) ? $_POST[$name] : $value;
	return $escape == TRUE ? daddslashes(stripslashes_deep($val)) : $val;
}

/**
 +------------------------------------------------------------------------------
 * 接收WEB服务器的POST参数
 +----------------------------------------------------------
 * @param string $name   参数名字
 * @param string $value  默认值
 * @param bool   $escape 是否转义
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function PA($array,$name, $value='', $escape = TRUE)
{
	$val = isset($array[$name]) && !empty($array[$name]) ? $array[$name] : $value;
	return $escape == TRUE ? daddslashes(stripslashes_deep($val)) : $val;
}

/**
 +------------------------------------------------------------------------------
 * 将字符转义,包括单引号和html代码
 +------------------------------------------------------------------------------
 * @param string $string
 * @param bool   $force
 +------------------------------------------------------------------------------
 * @return mixed
 +------------------------------------------------------------------------------
 */
function daddslashes($string, $force = 0) 
{
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			if(!is_numeric($string)){
				$string = htmlspecialchars(addslashes($string));
			}
		}
	}
	return $string;
}

/**
 +------------------------------------------------------------------------------
 * 去除转义
 +------------------------------------------------------------------------------
 * @param  string/array $value
 +------------------------------------------------------------------------------
 * @return mixed
 +------------------------------------------------------------------------------
 */
function stripslashes_deep($value)
{
    $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    return $value;
}

/**
 +------------------------------------------------------------------------------
 * 控制器名字和CALSS转换
 +----------------------------------------------------------
 * @param string $name 名字
 * @param string $cont Controller、Action区分
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function U($str,$cont=true){
	if(true===$cont){
		return str_replace(' ', '', ucwords(str_replace('-', ' ', $str))) . 'Controller';
	}else{
		return str_replace(' ', '', ucwords(str_replace('-', ' ', $str))) . 'Action';
	}
}

/**
 +------------------------------------------------------------------------------
 * 取得配置文件INI的信息
 +----------------------------------------------------------
 * @param string $node 节点名字
 * @param string $value 字段名字
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function INI($node,$value=''){
	GLOBAL $framework;
	if(''===$value){
		if(isset($framework[$node]) && !empty($framework[$node])){
			return $framework[$node];
		}else{
			return false;
		}
	}else{
		if(isset($framework[$node][$value]) && !empty($framework[$node][$value])){
			return $framework[$node][$value];
		}else{
			return false;
		}
	}
}

/**
 +------------------------------------------------------------------------------
 * 取得对象变量格式化输出结果
 +----------------------------------------------------------
 * @param string $value 变量对象
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function DUMP($value=''){
	ob_start();
    var_dump($value);
    return ob_get_clean();
}

/**
 +------------------------------------------------------------------------------
 * 取得图片的URL
 +----------------------------------------------------------
 * @param string $img_path 路径
 * @param string $img_name 名称
 * @param string $w 宽度
 * @param string $h 高度
 +----------------------------------------------------------
 * @return void
 +------------------------------------------------------------------------------
 */
function IMGURL($img_path, $img_name, $w=0, $h=0)
{
	$h = $h == 0 ? $w : $h;
	
	if (!empty($img_path)){
		$path = $img_path."/";
	}
	if ($w==0 && $h==0)
	{
		return FILE_PATH . "/" . $path . $img_name;
	} else {
		return FILE_PATH . "/" . $path . $img_name . "_" . $w . "x" . $h . ".jpg";
	}
}
	
/**
 +----------------------------------------------------------
 * 获取用户IP地址
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function getIp()
{
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
	{
		$onlineip = getenv('HTTP_CLIENT_IP');
	}
	elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
	{
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	}
	elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
	{
		$onlineip = getenv('REMOTE_ADDR');
	}
	elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
	{
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	return $onlineip;
}

function Isubstr($string, $sublen, $ext=true, $start=0)
{
    mb_internal_encoding ( "UTF-8" );

    $string = strip_tags(trim(html_entity_decode($string)));//去除HTML标签,空格



    if ($sublen == 0) return '';

    preg_match_all ( "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info );

    $k = 0;
    $count = count($info[0]);
    if($count <= $sublen){
        return $string;
    }
    $wordscut = '';
    for($i = 0; $i <$count; $i ++) {
        $wordscut .= $info [0] [$i];
        $k ++;
        if ($k >= $sublen) {
            break;
        }
    }
    return $ext ? $wordscut."...":$wordscut;
}


/**
 * 构造insert插入sql语句
 *
 * @param  string $table        表名
 * @param  array  $field        字段
 * @return string
 */
function insertSql($table, $option)
{
    $sql    = "INSERT INTO `".$table."` ";
    $field  = $value = "";
    foreach ($option as $f => $v) {
        if (is_string($v)) {
            $v = addslashes($v);
        }
        $field .= "`".$f."`,";
        $value .= "'".$v."',";
    }
    $sql .= " (".trim($field, ',').") VALUES (".trim($value, ',').")";
    return $sql;
}

/**
 * 构造update更新sql语句
 *
 * @param  string $table     表名
 * @param  array  $option    字段
 * @param  string $condition 查询条件
 * @return string
 */
function updateSql($table, $option, $condition)
{
    $sql    = "UPDATE `".$table."` SET ";
    $field  = '';
    foreach ($option as $f => $v) {
        if (is_string($v)) {
            $v = addslashes($v);
        }
        $field .= "`".$f."`='".$v."',";
    }
    $sql .= trim($field, ',')." WHERE ".$condition;
    return $sql;
}

/**
 * 跳转函数
 *
 * @access	public
 * @param	string	the URL
 * @param	string	the method: location or redirect
 * @return	string
 */
if ( ! function_exists('redirect')) {
    function redirect($uri = '', $method = 'location', $http_response_code = 302)
    {
        if ( ! preg_match('#^https?://#i', $uri)) {
            $uri = $uri;
        }

        switch($method) {
            case 'refresh'	: header("Refresh:0;url=".$uri);
                break;
            default		: header("Location: ".$uri, TRUE, $http_response_code);
            break;
        }
        exit;
    }
}

/**
 *  格式化显示出变量
 *
 *  @author Garbin
 *  @param  any
 *  @return void
 */
function debug($arr)
{
    echo '<pre>';
    array_walk(func_get_args(), create_function('&$item, $key', 'print_r($item);'));
    echo '</pre>';
    exit();
}

/**
 * 创建目录（如果该目录的上级目录不存在，会先创建上级目录）
 * 依赖于 ROOT_PATH 常量，且只能创建 ROOT_PATH 目录下的目录
 * 目录分隔符必须是 / 不能是 \
 *
 * @param   string  $absolute_path  绝对路径
 * @param   int     $mode           目录权限
 * @return  bool
 */
function imkdir($absolute_path, $mode = 0777)
{
    if (is_dir($absolute_path)) {
        return true;
    }

    $root_path      = UPLOAD_PATH;
    $relative_path  = str_replace($root_path, '', $absolute_path);
    $each_path      = explode('/', $relative_path);
    $cur_path       = $root_path; // 当前循环处理的路径
    foreach ($each_path as $path) {
        if ($path) {
            $cur_path = $cur_path . '/' . $path;
            if (!is_dir($cur_path)) {
                if (@mkdir($cur_path, $mode)) {
                    fclose(fopen($cur_path . '/index.htm', 'w'));
                }  else {
                    return false;
                }
            }
        }
    }
    return true;
}

function alert($msg) {
    header('Content-type: text/html; charset=UTF-8');
    echo json_encode(array('error' => 1, 'message' => $msg));
    exit;
}

define('UC_KEY', 'lx_crm');
/**
 *  uc自带函数2
 *
 * @access  public
 *
 * @return  string  $string
 */
function _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    $ckey_length = 4;
    $key = md5($key ? $key : UC_KEY);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++)
    {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++)
    {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++)
    {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE')
    {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
        {
            return substr($result, 26);
        }
        else
        {
            return '';
        }
    }
    else
    {
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}

/**
 *
 * 发送短信
 * @param sting $tel //发信发送的目的号码.多个号码之间用半角逗号隔开
 * @param sting $content //短信的内容
 */
function message_send($tel, $content)
{
    $key = '3b9c261e2c580f8a4d7d62d659f5c733';
    $remote_server = 'http://'.$_SERVER['HTTP_HOST'].'/message/send/';
    $post_string = '?key='.$key.'&tel='.$tel.'&content='.$content;
    $post_string = array(
        'key'=>$key,
        'tel'=>$tel,
        'content'=>$content
    );
    makeRequest($remote_server, $post_string);
}

function makeRequest($url, $param, $httpMethod = 'GET')
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
    }

    if ($httpMethod == 'GET') {
        curl_setopt($oCurl, CURLOPT_URL, $url . "?" . http_build_query($param));
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 1);
    } else {
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, 1);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 1);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, http_build_query($param));
    }

    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return FALSE;
    }
}
?>